# adjust observation windows in 'data', 'covr' and 'plotdim' into a same scale
# 
# @data: a dataframe of points
# @covr: a list of 'im' objects
# @plotdim: a vector of length and width of the plot
# Author: guochun
###############################################################################


#adjust windows for coravation
setwin=function(data,covr,plotdim){
	n=length(covr)
	x.min=x.max=y.min=y.max=numeric()
	for (i in 1:n){
		x.min[i]=covr[[i]]$xrange[1]
		x.max[i]=covr[[i]]$xrange[2]
		y.min[i]=covr[[i]]$yrange[1]
		y.max[i]=covr[[i]]$yrange[2]
	}
	x.max=min(x.max,plotdim[1])
	y.max=min(y.max,plotdim[2])
	x.min=max(x.min)
	y.min=max(y.min)
	win=owin(c(x.min,x.max),c(y.min,y.max))
	plotdim=c(x.max-x.min,y.max-y.min)
	
	data=data[which(data$gx>=x.min & data$gx<=x.max & data$gy>=y.min & data$gy<=y.max),]
	data$gx=data$gx-min(data$gx)
	data$gy=data$gy-min(data$gy)
	
	for (i in 1:n){
		covr[[i]]=covr[[i]][win]
		covr[[i]]$xrange=c(0,plotdim[1])
		covr[[i]]$yrange=c(0,plotdim[2])
		covr[[i]]$xcol=covr[[i]]$xcol-x.min
		covr[[i]]$yrow=covr[[i]]$yrow-y.min
	}
	
	return(list(plotdim,data,covr))
}
